﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Security;
using System.Security.Permissions;
using System.Security.AccessControl;
using System.Security.Principal;
using System.IO;
using System.ServiceProcess;

namespace Servicio.SMS.Movistar
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
        }

        // Give ACL permissions for Movistar.SMS.Service
        public override void Install(IDictionary stateSaver)
        {
            try
            {
                SecurityPermission permission = new SecurityPermission(PermissionState.Unrestricted);
                permission.Demand();

                AddLocalServiceAccess(Context.Parameters["dbPath"]);
                AddLocalServiceAccess(Context.Parameters["logPath"]);
            }
            catch (SecurityException)
            {
                throw new InstallException(
                    "01 - No tiene suficientes permisos para instalar esta aplicación.");
            }
            catch (Exception ex)
            {
                throw new InstallException("02 - " + ex.Message);
            }

            base.Install(stateSaver);
        }

        private void AddLocalServiceAccess(string sFilePath)
        {
            FileSecurity fFileACLs = File.GetAccessControl(sFilePath);

            fFileACLs.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), 
                FileSystemRights.Modify, AccessControlType.Allow));

            File.SetAccessControl(sFilePath, fFileACLs);
        }

        // Stop Service Movistar.SMS.Service
        public override void Uninstall(IDictionary savedState)
        {
            try
            {
                ServiceController smsService = new ServiceController("Movistar.SMS.Service");

                smsService.Stop();

                smsService.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 10));
            }
            catch { }

            base.Uninstall(savedState);
        }

        // Start Movistar.SMS.Service
        public override void Commit(IDictionary savedState)
        {
            try
            {
                ServiceController smsService = new ServiceController("Movistar.SMS.Service");

                smsService.Start();
            }
            catch (Exception ex)
            {
                throw new InstallException("03 - " + ex.Message);
            }

            base.Commit(savedState);
        }

        public override void Rollback(IDictionary savedState)
        {
            base.Rollback(savedState);
        }
    }
}
